package user_logic

import (
	"context"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"strings"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateUserLogic 更新用户
func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UserResponse, err error) {
	// 验证输入数据
	if req.ID <= 0 {
		return &types.UserResponse{
			Code:    500,
			Message: "无效的用户ID"}, fmt.Errorf("invalid user ID")
	}

	// 初始化更新字段和参数
	var updateFields []string
	var updateParams []interface{}

	// 如果密码不为空，则加密密码并添加到更新字段
	if req.Password != "" {
		hashedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
		if err != nil {
			return nil, fmt.Errorf("failed to hash password: %v", err)
		}
		hashedPassword := string(hashedPasswordBytes)
		updateFields = append(updateFields, "password = ?")
		updateParams = append(updateParams, hashedPassword)
	}

	// 动态添加其他字段到更新字段和参数
	if req.Username != "" {
		updateFields = append(updateFields, "username = ?")
		updateParams = append(updateParams, req.Username)
	}
	if req.Role != "" {
		updateFields = append(updateFields, "role = ?")
		updateParams = append(updateParams, req.Role)
	}
	if req.Email != "" {
		updateFields = append(updateFields, "email = ?")
		updateParams = append(updateParams, req.Email)
	}
	if req.Department != "" {
		updateFields = append(updateFields, "department = ?")
		updateParams = append(updateParams, req.Department)
	}

	// 如果没有任何字段需要更新，返回错误
	if len(updateFields) == 0 {
		return &types.UserResponse{
			Code:    500,
			Message: "没有提供任何更新字段"}, fmt.Errorf("no fields to update")
	}

	// 判断使用的数据库类型
	flag := l.svcCtx.Config.UseMysql

	// 构建更新查询语句
	tableName := l.svcCtx.Config.SQLite.Tables.UserInfoTable
	if flag {
		tableName = l.svcCtx.Config.Mysql.Tables.UserInfoTable
	}

	query := fmt.Sprintf("UPDATE %s SET %s WHERE id = ? AND deleted_at IS NULL", tableName, strings.Join(updateFields, ", "))
	updateParams = append(updateParams, req.ID)

	// 更新用户信息
	result, err := l.svcCtx.Conn.Exec(query, updateParams...)
	if err != nil {
		return &types.UserResponse{
			Code:    500,
			Message: "用户信息更新失败: " + err.Error()}, fmt.Errorf("failed to update user: %v", err)
	}

	// 获取受影响的行数
	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return nil, fmt.Errorf("failed to get rows affected: %v", err)
	}

	// 检查是否找到并更新了用户
	if rowsAffected == 0 {
		return &types.UserResponse{
			Code:    500,
			Message: "用户不存在"}, fmt.Errorf("user not found")
	}

	return &types.UserResponse{
		Code:    200,
		Message: "用户信息更新成功"}, nil
}
